const router = require('koa-router')()
const mongoose = require('mongoose')

const Image = mongoose.model('Image')
const stats = require('../helpers/stats')
const popular = require('../helpers/images')
const newestComments = require('../helpers/comments')

router.get('/', async (ctx, next) => {
  await Promise.all([
      Image.find().sort({timestamp: -1}),
      stats(),
      popular(),
      newestComments()
  ])
  .then(([images, stats, popular, newestComments]) => ctx.render('index',
      {images, stats, popular, newestComments}
  ))
  .catch(err => ctx.throw(500, err))
})

module.exports = router
